package cn.kduck.module.message.service.impl;

import cn.kduck.module.message.service.MailMessage;
import cn.kduck.module.message.service.MailMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.ObjectUtils;

import javax.activation.DataSource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MailMessageServiceImpl implements MailMessageService {

    private final MailProperties mailProperties;

    @Autowired
    private JavaMailSender mailSender;

    public MailMessageServiceImpl(MailProperties mailProperties){
        this.mailProperties = mailProperties;
    }

    @Override
    public void sendMail(MailMessage mailMessage) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            message.setSubject(mailMessage.getSubject());

            String fromUserName = mailMessage.getFromUserName();
            if(fromUserName == null){
                fromUserName = mailProperties.getUsername();
            }

            helper.setFrom(new InternetAddress(mailProperties.getUsername(), fromUserName, "UTF-8"));
            helper.setTo(mailMessage.getTo());

            if (!ObjectUtils.isEmpty(mailMessage.getBcc())){
                helper.setBcc(mailMessage.getBcc());
            }

            if (!ObjectUtils.isEmpty(mailMessage.getCc())){
                helper.setCc(mailMessage.getCc());
            }

            helper.setText(mailMessage.getContent(),true);
            Map<String, DataSource> inlineMap = mailMessage.getInlineMap();
            if(!inlineMap.isEmpty()){
                Iterator<String> cidIterator = inlineMap.keySet().iterator();
                while(cidIterator.hasNext()){
                    String cid = cidIterator.next();
                    helper.addInline(cid, inlineMap.get(cid));
                }
            }

            List<DataSource> attachmentList = mailMessage.getAttachmentList();
            for (DataSource dataSource : attachmentList) {
                helper.addAttachment(dataSource.getName(),dataSource);
            }

        } catch (Exception e) {
            throw new RuntimeException("构造邮件对象错误",e);
        }

        mailSender.send(message);
    }

}
